import axios from 'axios'
import config from '#/api.config'
import qs from 'qs'
import store from '@store'

import { CurrentTimeStr } from './Date'
import { MessageBox } from 'element-ui'
const service = axios.create({
  method: 'Post',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  },
  baseURL: config.financeUrl,
  timeout: 20000
})
const pending = []
const CancelToken = axios.CancelToken
const cancelPending = config => {
  pending.forEach((item, index) => {
    if (config) {
      if (item.u === config.url) {
        item.f() // 取消请求
        pending.splice(index, 1) // 移除当前请求记录
      }
    } else {
      item.f() // 取消请求
      pending.splice(index, 1) // 移除当前请求记录
    }
  })
}
service.interceptors.request.use(config => {
  // const _this = this
  if (
    localStorage.getItem('loginOutTime') &&
    CurrentTimeStr() > localStorage.getItem('loginOutTime')
  ) {
    /*
        1.取消当前请求
      */
    config.cancelToken = new CancelToken(c => {
      pending.push({ u: config.url, f: c })
    })
    cancelPending(config)
    MessageBox.confirm('你已被登出,请重新登录', '确定登出', {
      showCancelButton: false,
      confirmButtonText: '重新登录',
      type: 'warning'
    })
      .then(() => {
        store.dispatch('LogOut').then(() => {
          store.dispatch('toLogin').then(() => {})
        })
      })
      .catch(() => {
        store.dispatch('LogOut').then(() => {
          store.dispatch('toLogin').then(() => {})
        })
      })
  }
  return config
})

export async function getProject(fzrbh) {
  return service({
    url: 'tc_getzw_xminfo',
    data: qs.stringify({ fzrbh: fzrbh })
  })
    .then(res => res)
    .catch(error => error)
}
export async function getFzrbh() {
  return service({
    url: config.baseUrl + 'JPost',
    data: qs.stringify({
      query: 'vue_帐号课题组信息',
      课题组编号: localStorage.getItem('课题组编号')
    })
  })
    .then(res => res)
    .catch(error => error)
}
export async function deleteYYD(fzrbh, yydh) {
  return service({
    url: 'tc_delYYdh',
    data: qs.stringify({ fzrbh: fzrbh, str_yydh: yydh })
  })
    .then(res => res)
    .catch(error => error)
}
export async function saveBookingForm(fzrbh, xtlx, JsonStr) {
  return service({
    url: 'tc_saveYY',
    data: qs.stringify({
      fzrbh: fzrbh,
      xtlx: xtlx,
      JsonStr: JsonStr
    })
  })
    .then(res => res)
    .catch(error => error)
}
